﻿using System;
using System.Linq;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using logistics;
using Logistics.Configuration;
using Logistics.DataManage;
using Logistics.DataManage.DAL;
using Logistics.Print;
using Logistics.Utils;
using System.Collections.Generic;

namespace Logistics
{
    public delegate void DataChangedEventHandler(Object sender, EventArgs arg);
    /// <summary>
    /// Interaction logic for RecordEditWindow.xaml
    /// </summary>
    public partial class RecordEditWindow : Window
    {
        private String m_recordId = "";
        //private bool m_initflag = true;
        private BillDataInfo BillDataSource { get; set; }

        public event DataChangedEventHandler DataChanged;
        private void FireDataChanged()
        {
            if (this.DataChanged != null)
                this.DataChanged(this, new EventArgs());
        }

        /// <summary>
        /// 无参构造
        /// </summary>
        public RecordEditWindow()
            : this("")
        {
        }
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="recordId"></param>
        public RecordEditWindow(String recordId)
        {
            this.m_recordId = recordId;
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitData();
        }
        private void InitData()
        {
            //光标定位
            this.comboBoxReceiver.Focus();

            BillDataInfo lastBill = this.BillDataSource;

            this.BillDataSource = GetBillDataSource(this.m_recordId);
            if (lastBill != null)
            {
                this.BillDataSource.ReceivingClerk = lastBill.ReceivingClerk;
                this.BillDataSource.DesSiteId = lastBill.DesSiteId;
                this.BillDataSource.DesOutletList = lastBill.DesOutletList;
                this.BillDataSource.DesOutletId = lastBill.DesOutletId;

                //this.BillDataSource.ReceiverName = lastBill.ReceiverName;
                //this.BillDataSource.ReceiverPhone = lastBill.ReceiverPhone;
                //this.BillDataSource.ReceiverCellPhone = lastBill.ReceiverCellPhone;
                //this.BillDataSource.ReceiverAddress = lastBill.ReceiverAddress;

            }

            this.BillDataSource.PropertyChanged += new PropertyChangedEventHandler(BillDataSource_PropertyChanged);
            this.DataContext = this.BillDataSource;
        }

        #region 数据交互
        void BillDataSource_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            BillDataInfo BillInfo = sender as BillDataInfo;
            String Prop = e.PropertyName;
            switch (Prop)
            {
                case "SenderPhone":
                case "SenderCellPhone":
                case "ReceiverPhone":
                case "ReceiverCellPhone":
                    {
                        break;
                    }
                case "DesSiteId":
                    {
                        GenerateGoodsCode(BillInfo);//生成货号
                        FillDesOutletList(BillInfo);//填充目的网点
                        CalculateFreightFee(BillInfo);//计算运费

                        break;
                    }
                case "BillGoodsLength":
                case "BillGoodsWidth":
                case "BillGoodsHeight":
                    {
                        CalculateVolume(BillInfo);//计算体积
                        break;
                    }
                case "BillGoodsVolume":
                case "BillGoodsWeight":
                    {
                        CalculateFreightFee(BillInfo);//计算运费
                        break;
                    }
                case "BillGoodsCount":
                    {
                        BillInfo.BillTagCount = BillInfo.BillGoodsCount;
                        GenerateGoodsCode(BillInfo);//生成货号
                        CalculateFreightFee(BillInfo);//计算运费
                        break;
                    }
                case "VAAgencyFund"://代收费
                    {
                        CalcAgencyFundHandlingCharge(BillInfo);
                        CalcStartSiteTotalFee(BillInfo);
                        GetEndSiteTotalFee(BillInfo);
                        break;
                    }
                case "PayType":                 //支付方式
                    {
                        if (BillInfo.PayType == CONST_PAYMENT_Type_PAYNOW_KEY)//现付
                            BillInfo.VADeliveryFeeWindow = CONST_Window_Station_SRC_KEY;//源站点收
                        else//提付
                            BillInfo.VADeliveryFeeWindow = CONST_Window_Station_DES_KEY;//目的站收
                        break;
                    }
                case "BillFreightFee":          //运单费
                    {
                        //根据运费计算送货费
                        CalculateVADeliveryFee(BillInfo);
                        CalcStartSiteTotalFee(BillInfo);
                        GetEndSiteTotalFee(BillInfo);
                        break;
                    }
                case "VADeliveryFeeWindow":     //送货费支付窗口
                case "VADeliveryFee":           //送货费
                case "VAInsuranceFeeWindow":    //保险费支付窗口
                case "VAClaimedValue":
                    {
                        CalculateVAInsuranceFee(BillInfo);
                        CalcStartSiteTotalFee(BillInfo);
                        GetEndSiteTotalFee(BillInfo);
                        break;
                    }
                case "VAInsuranceFee":          //保险费
                    {
                        CalcStartSiteTotalFee(BillInfo);
                        GetEndSiteTotalFee(BillInfo);
                        break;
                    }
                case "VAAgencyFundHandlingCharge"://代收款手续费
                case "VAAdvance":               //垫付费
                case "VAForwardFee":            //转寄费
                    {
                        CalcStartSiteTotalFee(BillInfo);
                        GetEndSiteTotalFee(BillInfo);
                        break;
                    }
                case "BillCommDeteriorateNoPay":
                case "BillCommDamageNoPay":
                case "BillCommAttachReceipts":
                case "BillCommWaitFax":
                    {
                        CalculateComment(BillInfo);
                        break;
                    }
            }
        }
        /// <summary>
        /// 计算体积
        /// </summary>
        /// <param name="BillInfo"></param>
        private void CalculateVolume(BillDataInfo BillInfo)
        {
            float volumeCM = BillInfo.BillGoodsLength * BillInfo.BillGoodsWidth * BillInfo.BillGoodsHeight;
            BillInfo.BillGoodsVolume = Convert.ToInt32(Round(volumeCM / 1000000, 2));
        }
        /// <summary>
        /// 量方称重计算运费
        /// </summary>
        /// <param name="BillInfo"></param>
        private void CalculateFreightFee(BillDataInfo BillInfo)
        {
            string startSiteId = BillInfo.StartSiteId;
            string endSiteId = BillInfo.DesSiteId;
            float _weight = BillInfo.BillGoodsWeight;
            float _volume = BillInfo.BillGoodsVolume;
            int count = BillInfo.BillGoodsCount;
            if (count > 0 && (_weight > 0 || _volume > 0))
            {
                double freight = ChargesMgr.GetFreightCharge(startSiteId, endSiteId, _weight, _volume);
                double total = freight * count;//计算多件货物总运费
                BillInfo.BillFreightFee = Convert.ToInt32(Round(total, 0));
            }
        }
        /// <summary>
        /// 计算保价费
        /// </summary>
        /// <param name="BillInfo"></param>
        private void CalculateVAInsuranceFee(BillDataInfo BillInfo)
        {
            if (BillInfo.VAClaimedValue <= 0) return;
            string site_route_S = BillInfo.StartSiteId;
            string site_route_E = BillInfo.DesSiteId;
            ORoute route = RouteDAO.GetRouteByStartEndId(site_route_S, site_route_E);
            if (route != null)
            {
                string routeID = route.RouteID;

                float _Insured = ChargesMgr.CalcInsuranceFee(BillInfo.VAClaimedValue, routeID);
                BillInfo.VAInsuranceFee = Convert.ToInt32(Round(Convert.ToDouble(_Insured), 0));
                //this.txtAdvance.Focus();
            }
        }
        /// <summary>
        /// 根据运费计算送货费
        /// </summary>
        /// <param name="BillInfo"></param>
        private void CalculateVADeliveryFee(BillDataInfo BillInfo)
        {
            //if (BillInfo.BillFreightFee <= 0) return;
            string site_route_S = BillInfo.StartSiteId;
            string site_route_E = BillInfo.DesSiteId;
            ORoute route = RouteDAO.GetRouteByStartEndId(site_route_S, site_route_E);
            if (route != null)
            {
                string routeID = route.RouteID;

                float _Insured = ChargesMgr.CalcDeliveryFee(BillInfo.BillFreightFee, routeID);
                BillInfo.VADeliveryFee = Convert.ToInt32(Round(Convert.ToDouble(_Insured), 0));
            }
        }

        /// <summary>
        /// 计算代收款手续费
        /// </summary>
        /// <param name="BillInfo"></param>
        private void CalcAgencyFundHandlingCharge(BillDataInfo BillInfo)
        {
            if (BillInfo.VAAgencyFund <= 0) return;
            string site_route_S = BillInfo.StartSiteId;
            string site_route_E = BillInfo.DesSiteId;
            ORoute route = RouteDAO.GetRouteByStartEndId(site_route_S, site_route_E);
            if (route != null)
            {
                string routeID = route.RouteID;
                float _AgencyFund = ChargesMgr.CalcAgencyFundHandlingCharge(BillInfo.VAAgencyFund, routeID);
                BillInfo.VAAgencyFundHandlingCharge = Convert.ToInt32(Round(Convert.ToDouble(_AgencyFund), 0));
            }
        }

        /// <summary>
        /// 实现数据的四舍五入法
        /// </summary>
        private double Round(double v, int x)
        {
            if (v.ToString().Contains("."))
            {
                string s = "0.";
                s += v.ToString().Split('.')[1];
                if (Convert.ToDouble(s) > 0)//有小数
                {
                    int vv = Convert.ToInt32(v.ToString().Split('.')[0]);
                    if (Convert.ToDouble(s) > 0.5 || Convert.ToDouble(s) == 0.5)//进一
                    {
                        vv += 1;
                    }

                    return vv;
                }
                else
                {
                    return v;
                }
            }
            else
            {
                return v;
            }
        }

        /// <summary>
        /// 填充目的网点列表
        /// </summary>
        /// <param name="BillInfo"></param>
        private void FillDesOutletList(BillDataInfo BillInfo)
        {
            var dict = OutletsDAO.GetOutletsNamesBySiteId(BillInfo.DesSiteId);
            BillInfo.DesOutletList = dict;
            if (dict != null && dict.Count > 0)
            {
                BillInfo.DesOutletId = dict.Keys.First();
            }
        }
        /// <summary>
        /// 响应备注
        /// </summary>
        /// <param name="BillInfo"></param>
        private void CalculateComment(BillDataInfo BillInfo)
        {
            string comm = string.Empty;
            if (BillInfo.BillCommDeteriorateNoPay)
                comm += "变质不赔，";
            if (BillInfo.BillCommDamageNoPay)
                comm += "损坏不赔，";
            if (BillInfo.BillCommAttachReceipts)
                comm += "附单，";
            if (BillInfo.BillCommWaitFax)
                comm += "等原票或传真发货";
            if (comm.Length > 0 && comm.EndsWith("，"))
                comm = comm.Substring(0, comm.Length - 1);
            BillInfo.BillComment = comm;
        }
        private void GenerateGoodsCode(BillDataInfo BillInfo)
        {
            //生成货号
            string MachineNum = GlobalObjects.GSetting.MachineID;
            String startSiteId = GlobalObjects.CurrentUser.SiteID;
            String endSiteId = BillInfo.DesSiteId;
            int count = BillInfo.BillGoodsCount;
            if (!String.IsNullOrWhiteSpace(MachineNum) && !String.IsNullOrWhiteSpace(startSiteId) &&
                !String.IsNullOrWhiteSpace(endSiteId))
                BillInfo.BillGoodsCode = IdentityMrg.GetGoodsCode(startSiteId, endSiteId, MachineNum, count, BillInfo.BillCode);
        }

        /// <summary>
        /// 查找客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageButton_Click(object sender, RoutedEventArgs e)
        {
            Button Btn = sender as Button;
            String arg = Btn.CommandParameter as String;

            //收货人
            if (arg == "ReceiverPhone" || arg == "ReceiverCellPhone")
            {
                String outletId = this.BillDataSource.DesOutletId;
                CheckUser frmUser = new CheckUser(outletId, null);
                frmUser.ShowDialog();
                if (!string.IsNullOrEmpty(frmUser.Custom_ID))
                {
                    OCustomer customer = CustomerDAO.GetCustomerById(frmUser.Custom_ID);
                    this.BillDataSource.ReceiverCode = customer.CustomID;
                    this.BillDataSource.ReceiverAddress = customer.CompanyAddress;
                    this.BillDataSource.ReceiverCellPhone = customer.CustomMobile;
                    this.BillDataSource.ReceiverName = customer.CustomName;
                    this.BillDataSource.ReceiverPhone = customer.CustomTel;

                    Keyboard.Focus(this.txtSenderPhone);
                }
                else
                {
                    Keyboard.Focus(this.txtReceiverCellPhone);
                }
            }
            else//发货人
            {
                //String outletId = GlobalObjects.CurrentUser.OutletId;
                String outletId = this.BillDataSource.StartOutletId;
                CheckUser frmUser = new CheckUser(outletId, null);
                frmUser.ShowDialog();
                if (!string.IsNullOrEmpty(frmUser.Custom_ID))
                {
                    OCustomer customer = CustomerDAO.GetCustomerById(frmUser.Custom_ID);
                    this.BillDataSource.SenderCode = customer.CustomID;
                    this.BillDataSource.SenderAddress = customer.CompanyAddress;
                    this.BillDataSource.SenderCellPhone = customer.CustomMobile;
                    this.BillDataSource.SenderName = customer.CustomName;
                    this.BillDataSource.SenderPhone = customer.CustomTel;
                    this.BillDataSource.VABankAccount = customer.BankNum;
                    if (!String.IsNullOrWhiteSpace(customer.BankName))
                        this.BillDataSource.VABank = customer.BankName;

                    Keyboard.Focus(this.txtGoodsName);
                }
                else
                {
                    Keyboard.Focus(this.txtSenderCellPhone);
                }
            }
        }
        /// <summary>
        /// 焦点切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)//切换焦点
            {
                UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
                if (elementWithFocus != null)
                {
                    bool moveFocus = TryToAutoFillPhoneNumber(elementWithFocus);
                    if (moveFocus)
                    {
                        TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
                        elementWithFocus.MoveFocus(request);
                    }
                }
                e.Handled = true;
            }
        }
        /// <summary>
        /// CTRL+S
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommandBinding_SaveData_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.BtnSave_Click(this.BtnSave, new RoutedEventArgs());
        }
        #endregion

        #region 数据保存处理
        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            String error = ValidateInputFields();
            if (!String.IsNullOrEmpty(error))
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(error, "数据验证错误", MessageBoxButton.OK, MessageBoxImage.Stop);
                return;
            }
            try
            {
                //保存 
                SaveBill();
                FireDataChanged();
            }
            catch (Exception ex)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(ex.Message, "数据保存错误", MessageBoxButton.OK, MessageBoxImage.Stop);
                return;
            }
            try
            {
                //打印
                PrinterUtils.PrintWayBill(this.BillDataSource.BillCode);
                PrinterUtils.PrintWayBillTags(this.BillDataSource.BillCode, this.BillDataSource.BillTagCount);
                if (!String.IsNullOrEmpty(this.m_recordId))
                {
                    //修改完成后关闭窗口
                    this.Close();
                }
                else
                {
                    //m_initflag = false;
                    //保存成功后清空窗体控件值
                    this.InitData();
                }
            }
            catch (Exception ex)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show(ex.Message, "打印错误", MessageBoxButton.OK, MessageBoxImage.Stop);
                return;
            }
        }

        private String ValidateInputFields()
        {
            string _Destinations = this.BillDataSource.DesSiteId;//目的地站点
            string _Destinations2 = this.BillDataSource.DesOutletId;//目的网点
            string _ConsigneeTel = this.BillDataSource.ReceiverPhone;
            string _ConsigneeMobile = this.BillDataSource.ReceiverCellPhone;
            string _ConsignorTel = this.BillDataSource.SenderPhone;
            string _ConsignorMobile = this.BillDataSource.SenderCellPhone;
            float _Fee = this.BillDataSource.BillFreightFee;
            float _Collection = this.BillDataSource.VAAgencyFund;

            string waybillID = this.BillDataSource.BillCode;
            if (String.IsNullOrEmpty(this.BillDataSource.BillGoodsName))
                return "货物名称填写不完整";
            if (this.BillDataSource.DesSiteList.Count == 0)
                return "请联系管理员完善目的地信息";
            if (String.IsNullOrEmpty(this.BillDataSource.ReceiverName))
                return "收货人不能为空！";

            #region 有代收款的判定
            if (_Collection > 0)//有代收款
            {
                string col = GlobalObjects.GSetting.ConsignorFlags;
                if (!string.IsNullOrEmpty(col))
                {
                    char[] tag = col.ToCharArray();
                    if (tag[0] == '1' && string.IsNullOrEmpty(this.BillDataSource.SenderName))
                        return "有代收款时，发货人姓名不能为空！";
                    if (tag[1] == '1' && string.IsNullOrEmpty(this.BillDataSource.SenderPhone))
                        return "有代收款时，发货人电话不能为空！";
                    if (tag[2] == '1' && string.IsNullOrEmpty(this.BillDataSource.SenderCellPhone))
                        return "有代收款时，发货人手机不能为空！";
                    if (tag[3] == '1' && string.IsNullOrEmpty(this.BillDataSource.VABankAccount))
                        return "有代收款时，发货人银行卡号不能为空！";
                }
            }
            #endregion

            if (!string.IsNullOrEmpty(_ConsigneeMobile) &&
                !StringUtils.IsValidCellPhoneNumer(_ConsigneeMobile))
                return "收货人手机格式不正确";
            if (!string.IsNullOrEmpty(_ConsignorMobile) &&
                !StringUtils.IsValidCellPhoneNumer(_ConsignorMobile))
                return "发货人手机格式不正确";
            if (!string.IsNullOrEmpty(_ConsigneeTel) &&
                !StringUtils.IsValidTel(_ConsigneeTel))
                return "请确保录入收货人的电话号码信息完整有效";
            if (!string.IsNullOrEmpty(_ConsignorTel) &&
                !StringUtils.IsValidTel(_ConsignorTel))
                return "请录确保入发货人的电话号码信息信息完整有效";
            if (_Destinations == "-1" || _Destinations2 == "-1")
                return "请选择货物运输的目的地";
            if (this.BillDataSource.BillGoodsCount <= 0)
                return "件数必须大于0";
            if (string.IsNullOrWhiteSpace(this.BillDataSource.BillPackageType))
                return "包装形式不能为空";
            if (this.BillDataSource.VAForwardFee > 0 && String.IsNullOrEmpty(this.BillDataSource.VAForwardAddr))
                return "请选择转寄地";
            return "";
        }

        private void SaveBill()
        {
            String BillCode = string.Empty;
            if (!String.IsNullOrEmpty(this.txtBillCode_Hid.Text))
            {
                BillCode = this.txtBillCode_Hid.Text;
            }
            else
            {
                //新建运单号
                String localMachineNo = GlobalObjects.GSetting.MachineID;
                BillCode = IdentityMrg.GetNewBillCode(GlobalObjects.CurrentUser.OutletId, this.BillDataSource.DesOutletId, localMachineNo);
            }
            this.BillDataSource.BillCode = BillCode;
            //生成货号
            GenerateGoodsCode(this.BillDataSource);

            OWaybill model = new OWaybill();
            //model.WaybillID = this.BillDataSource.BillCode;//运单编号
            model.WaybillID = BillCode;//运单编号
            model.Code = BillCode;//排序单号
            model.Origin = GlobalObjects.CurrentUser.SiteID;//原寄地的站点
            model.OriginNetWork = this.BillDataSource.StartOutletId;//原寄的网点
            model.Destinations = this.BillDataSource.DesSiteId;//目的地站点
            model.DestinationsNetwork = this.BillDataSource.DesOutletId;//目的网点
            //model.ConsigneeID = this.BillDataSource.ReceiverCode;//收货人的编号(客户端与服务器端可能不一致，客户端不用处理)
            model.ConsigneeTel = this.BillDataSource.ReceiverPhone;
            model.ConsigneeMobile = this.BillDataSource.ReceiverCellPhone;
            model.ConsigneeAddress = this.BillDataSource.ReceiverAddress;
            model.Consigneeor = this.BillDataSource.ReceiverName;
            //model.ConsignorDate = this.BillDataSource.SendDate;//不需要初始值
            model.Consignor = this.BillDataSource.SenderName;
            //model.ConsignorID = this.BillDataSource.SenderCode;//发货人的编号(客户端与服务器端可能不一致，客户端不用处理)
            model.ConsignorTel = this.BillDataSource.SenderPhone;
            model.ConsignorMobile = this.BillDataSource.SenderCellPhone;
            model.ConsignorAddress = this.BillDataSource.SenderAddress;
            //model.ConsignorDutyID = this.BillDataSource.ReceivingClerk;//收货员工：2013-9-12为了和BS端保持一致,此字段不赋值
            model.ConsignorCardID = this.BillDataSource.VABankAccount;
            model.ConsignorBank = this.BillDataSource.VABank;       //银行名称
            model.GoodsName = this.BillDataSource.BillGoodsName;
            model.Numbers = this.BillDataSource.BillGoodsCount;
            model.PackageType = this.BillDataSource.BillPackageType;

            #region 量方称重运费
            model.Freight = this.BillDataSource.BillFreightFee;//运费
            model.OriginAccept = this.BillDataSource.BillFeeSRC;//源站点收
            model.DestinationAccept = this.BillDataSource.BillFeeDES;//目的站收

            model.Weight = this.BillDataSource.BillGoodsWeight;
            model.Longth = this.BillDataSource.BillGoodsLength;
            model.Width = this.BillDataSource.BillGoodsWidth;
            model.Height = this.BillDataSource.BillGoodsHeight;
            model.Volume = this.BillDataSource.BillGoodsVolume;
            #endregion
            model.OrderAcceptFee = this.BillDataSource.VAAgencyFund;//应收代收款:2013-9-12为了和BS端保持一致,OrderAcceptFee=CollectionFee
            model.CollectionFee = this.BillDataSource.VAAgencyFund;//代收款
            model.CollectionServicesFee = this.BillDataSource.VAAgencyFundHandlingCharge;//代收款服务费  
            model.InsuranceFee = this.BillDataSource.VAClaimedValue;//货物价值
            model.InsuredServicesFee = this.BillDataSource.VAInsuranceFee;//保价费            
            model.NoteDelivery = this.BillDataSource.VANoticeDelivery;
            model.NoteDeliveryFee = this.BillDataSource.VANoticDeliveryFee;
            string strBacktype = "";
            if (this.BillDataSource.VAReceiptTypeReceipt)
            {
                strBacktype += CONST_BackTypes[0] + ",";
            }
            if (this.BillDataSource.VAReceiptTypeStamp)
            {
                strBacktype += CONST_BackTypes[1] + ",";
            }
            if (this.BillDataSource.VAReceiptTypeIDNum)
            {
                strBacktype += CONST_BackTypes[2];
            }
            model.BackType = strBacktype;//签回单类型

            model.Advanced = this.BillDataSource.VAAdvance;
            model.DeliveryCharges = this.BillDataSource.VADeliveryFee;//送货费
            model.ForwardFee = this.BillDataSource.VAForwardFee; //转寄费
            model.ForwardAddress = this.BillDataSource.VAForwardAddr; //转寄地
            model.ForwardCompany = this.BillDataSource.VACollaborativeLogistics;//合作物流
            if (this.BillDataSource.DeliveryService)
                model.ServicesMode = CONST_DeliveryServiceMode_Delivers;
            else
                model.ServicesMode = CONST_DeliveryServiceMode_SelfCollection;

            model.PayMode = this.BillDataSource.PayType;
            model.GoodsCode = this.BillDataSource.BillGoodsCode;
            model.CreatedDate = this.BillDataSource.CreateDate;
            model.KaiPiaoDate = model.CreatedDate;//开票日期同创建日期
            model.CreateUser = GlobalObjects.CurrentUser.UserID;
            model.Memo = this.BillDataSource.BillComment;
            model.PreAcceptFee = this.BillDataSource.VAPrepay;

            //保持不变的值
            model.BackFormFee = "0";//签回单服务费
            model.BackForm = "";//签回单号
            model.IsUsed = true;//是否可用
            model.SendPay = "";//寄方应付
            model.CollectionState = 1;//暂设
            model.GoodsState = 1;//暂设
            model.BillingWeight = 0;
            model.Column1 = this.BillDataSource.VAInsuranceFeeWindow;//1-保价费是源站点收,2-保价费是目的站收
            model.Column2 = this.BillDataSource.VADeliveryFeeWindow;//1-送货费是 源站点收,2-送货费是 目的站收
            model.Column3 = this.BillDataSource.ReceivingClerk;

            //新加
            model.presendfee = 0;
            model.packagefee = 0;
            model.packagenumber = 0;
            model.carstate = "0";
            model.collectionstate = "1";
            model.returnstate = "0";
            model.sendstate = "0";
            model.prestate = "0";
            model.realweight = 0;
            model.sendpay = 0;

            model.shifakuan = 0;
            model.shishoudaikuan=0;
            model.fashouxufei = "0";

            bool success = false;
            string waybillID = this.BillDataSource.BillCode;
            bool exist = WaybillDAO.IsBillExist(waybillID);
            if (exist)
                success = WaybillDAO.UpdateBill(model);
            else
                success = WaybillDAO.AddBill(model);

            if (success)
            {
                CustomerDAO.JudeConsignee(model);
                CustomerDAO.JudeConsignor(model);
                BillLogsDAO.AddWaybillInforLogs(GlobalObjects.CurrentUser.RealName, model.WaybillID, "添加", "录入成功", SitesDAO.GetSiteName(model.Origin));
            }
        }
        #endregion

        private void BtnReset_Click(object sender, RoutedEventArgs e)
        {
            this.InitData();
        }

        #region  辅助方法
        /// <summary>
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private bool IsMobilePhoneNumber(String number)
        {
            if (!String.IsNullOrWhiteSpace(number))
            {
                number = number.Trim();
                if (number.Length == 11 && !number.StartsWith("0"))
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 尝试自动填充收货人或发货人的手机
        /// </summary>
        /// <param name="elementWithFocus"></param>
        /// <returns>是否继续移动焦点</returns>
        private bool TryToAutoFillPhoneNumber(UIElement elementWithFocus)
        {
            if (elementWithFocus != null && elementWithFocus is TextBox)
            {
                TextBox txtBox = elementWithFocus as TextBox;
                if (this.txtReceiverPhone == txtBox)//座机
                {
                    return TryToAutoFillReceiverPhoneNumber(txtBox.Text, this.BillDataSource.DesOutletId);
                }
                if (this.txtReceiverCellPhone == txtBox)//手机
                {
                    return TryToAutoFillReceiverCellPhoneNumber(txtBox.Text, this.BillDataSource.DesOutletId);
                }
                if (this.txtSenderPhone == txtBox)//座机
                {
                    return TryToAutoFillSenderPhoneNumber(txtBox.Text, this.BillDataSource.StartOutletId);
                }
                if (this.txtSenderCellPhone == txtBox)//手机
                {
                    return TryToAutoFillSenderCellPhoneNumber(txtBox.Text, this.BillDataSource.StartOutletId);
                }
            }
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private bool TryToAutoFillReceiverPhoneNumber(String number, String outletId)
        {
            //OCustomer customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            IList<OCustomer> customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            if (customer != null)//找到匹配用户，自动填充
            {
                if (customer.Count == 1)
                {
                    this.BillDataSource.ReceiverPhone = customer[0].CustomTel;
                    this.BillDataSource.ReceiverCellPhone = customer[0].CustomMobile;
                    this.BillDataSource.ReceiverName = customer[0].CustomName;
                    this.BillDataSource.ReceiverAddress = customer[0].CompanyAddress;

                    //跳跃光标,转到发货人
                    this.txtSenderPhone.Focus();
                    return false;
                }
                else
                {
                    CheckUser frmUser = new CheckUser(outletId, number);
                    frmUser.ShowDialog();

                    OCustomer cus = CustomerDAO.GetCustomerById(frmUser.Custom_ID);
                    if (cus == null)
                    {
                        //this.txtSenderPhone.Focus();
                        return false;
                    }
                    else
                    {
                        this.BillDataSource.ReceiverCode = cus.CustomID;
                        this.BillDataSource.ReceiverAddress = cus.CompanyAddress;
                        this.BillDataSource.ReceiverCellPhone = cus.CustomMobile;
                        this.BillDataSource.ReceiverName = cus.CustomName;
                        this.BillDataSource.ReceiverPhone = cus.CustomTel;

                        Keyboard.Focus(this.txtSenderPhone);
                        return false;
                    }
                }

            }
            else
            {
                //检查是否把手机填入座机号中
                bool isMobile = IsMobilePhoneNumber(number);
                if (isMobile)
                {
                    this.BillDataSource.ReceiverPhone = "";
                    this.BillDataSource.ReceiverCellPhone = number;
                    //跳跃一下
                    this.txtReceiver.Focus();
                    return false;
                }
                else
                {
                    this.txtReceiverCellPhone.Focus();
                    return false;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private bool TryToAutoFillReceiverCellPhoneNumber(String number, String outletId)
        {
            //OCustomer customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            IList<OCustomer> customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            if (customer != null)//找到匹配用户，自动填充
            {
                if (customer.Count == 1)
                {
                    this.BillDataSource.ReceiverPhone = customer[0].CustomTel;
                    this.BillDataSource.ReceiverCellPhone = customer[0].CustomMobile;
                    this.BillDataSource.ReceiverName = customer[0].CustomName;
                    this.BillDataSource.ReceiverAddress = customer[0].CompanyAddress;

                    //跳跃光标,转到发货人
                    this.txtSenderPhone.Focus();
                    return false;
                }
                else
                {
                    CheckUser frmUser = new CheckUser(outletId, number);
                    frmUser.ShowDialog();

                    OCustomer cus = CustomerDAO.GetCustomerById(frmUser.Custom_ID);
                    if (cus == null)
                    {
                        //this.txtSenderPhone.Focus();
                        return false;
                    }
                    else
                    {

                        this.BillDataSource.ReceiverCode = cus.CustomID;
                        this.BillDataSource.ReceiverAddress = cus.CompanyAddress;
                        this.BillDataSource.ReceiverCellPhone = cus.CustomMobile;
                        this.BillDataSource.ReceiverName = cus.CustomName;
                        this.BillDataSource.ReceiverPhone = cus.CustomTel;

                        Keyboard.Focus(this.txtSenderPhone);
                        return false;
                    }
                }
            }
            else
            {
                this.txtReceiver.Focus();
                return false;
            }
        }
        private bool TryToAutoFillSenderPhoneNumber(String number, String outletId)
        {
            //OCustomer customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            IList<OCustomer> customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            if (customer != null)//找到匹配用户，自动填充
            {
                if (customer.Count == 1)
                {
                    this.BillDataSource.SenderPhone = customer[0].CustomTel;
                    this.BillDataSource.SenderCellPhone = customer[0].CustomMobile;
                    this.BillDataSource.SenderName = customer[0].CustomName;
                    this.BillDataSource.SenderAddress = customer[0].CompanyAddress;
                    this.BillDataSource.VABank = customer[0].BankName;
                    this.BillDataSource.VABankAccount = customer[0].BankNum;

                    //跳跃光标,转到货物名称
                    this.txtGoodsName.Focus();
                    return false;
                }
                else
                {
                    CheckUser frmUser = new CheckUser(outletId, number);
                    frmUser.ShowDialog();

                    OCustomer cus = CustomerDAO.GetCustomerById(frmUser.Custom_ID);
                    if (cus == null)
                    {
                        //this.txtSenderPhone.Focus();
                        return false;
                    }
                    else
                    {
                        this.BillDataSource.SenderCode = cus.CustomID;
                        this.BillDataSource.SenderAddress = cus.CompanyAddress;
                        this.BillDataSource.SenderCellPhone = cus.CustomMobile;
                        this.BillDataSource.SenderName = cus.CustomName;
                        this.BillDataSource.SenderPhone = cus.CustomTel;
                        this.BillDataSource.VABankAccount = cus.BankNum;
                        if (!String.IsNullOrWhiteSpace(cus.BankName))
                            this.BillDataSource.VABank = cus.BankName;

                        Keyboard.Focus(this.txtGoodsName);
                        return false;
                    }
                }
            }
            else
            {
                //检查是否把手机填入座机号中
                bool isMobile = IsMobilePhoneNumber(number);
                if (isMobile)
                {
                    this.BillDataSource.SenderPhone = "";
                    this.BillDataSource.SenderCellPhone = number;
                    //跳跃一下
                    this.txtSender.Focus();
                    return false;
                }
                else
                {
                    this.txtSenderCellPhone.Focus();
                    return false;
                }
            }
        }
        private bool TryToAutoFillSenderCellPhoneNumber(String number, String outletId)
        {
            //OCustomer customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            IList<OCustomer> customer = CustomerDAO.GetCustomerByPhoneNumber(number, outletId);
            if (customer != null)//找到匹配用户，自动填充
            {
                if (customer.Count == 1)
                {
                    this.BillDataSource.SenderPhone = customer[0].CustomTel;
                    this.BillDataSource.SenderCellPhone = customer[0].CustomMobile;
                    this.BillDataSource.SenderName = customer[0].CustomName;
                    this.BillDataSource.SenderAddress = customer[0].CompanyAddress;
                    this.BillDataSource.VABank = customer[0].BankName;
                    this.BillDataSource.VABankAccount = customer[0].BankNum;


                    //跳跃光标,转到货物名称
                    this.txtGoodsName.Focus();
                    return false;
                }
                else
                {
                    CheckUser frmUser = new CheckUser(outletId, number);
                    frmUser.ShowDialog();
                    OCustomer cus = CustomerDAO.GetCustomerById(frmUser.Custom_ID);
                    if (cus == null)
                    {
                        //this.txtSenderPhone.Focus();
                        return false;
                    }
                    else
                    {
                        this.BillDataSource.SenderCode = cus.CustomID;
                        this.BillDataSource.SenderAddress = cus.CompanyAddress;
                        this.BillDataSource.SenderCellPhone = cus.CustomMobile;
                        this.BillDataSource.SenderName = cus.CustomName;
                        this.BillDataSource.SenderPhone = cus.CustomTel;
                        this.BillDataSource.VABankAccount = cus.BankNum;
                        if (!String.IsNullOrWhiteSpace(cus.BankName))
                            this.BillDataSource.VABank = cus.BankName;

                        Keyboard.Focus(this.txtGoodsName);
                        return false;
                    }
                }
            }
            else
            {
                //跳跃一下
                this.txtSender.Focus();
                return false;
            }
        }
        #endregion


        private void txtClaimedValue_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (String.IsNullOrEmpty(this.txtClaimedValue.Value.ToString()))
            {
                this.txtClaimedValue.Value = 0;
                this.txtInsuranceFee.Value = 0;
            }
        }

        private void txtFreightFee_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (String.IsNullOrEmpty(this.txtFreightFee.Value.ToString()))
            {
                this.txtFreightFee.Value = 0;
            }
        }

        private void txtAgencyFund_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (String.IsNullOrEmpty(this.txtAgencyFund.Value.ToString()))
            {
                this.txtAgencyFund.Value = 0;
            }
        }

        private void txtAdvance_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (String.IsNullOrEmpty(this.txtAdvance.Value.ToString()))
            {
                this.txtAdvance.Value = 0;
            }
        }

        private void txtDeliveryFee_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (String.IsNullOrEmpty(this.txtDeliveryFee.Value.ToString()))
            {
                this.txtDeliveryFee.Value = 0;
            }
        }
    }
}
